package com.xdl.moudle.shiro.controller;

import com.xdl.moudle.shiro.util.BaseController;
import com.xdl.moudle.shiro.util.MD5Utils;
import com.xdl.moudle.utils.util.apibase.APIBaseResult;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class ShiroController extends BaseController {


	@GetMapping("/login")
	@ResponseBody
	public APIBaseResult login() {
		return APIBaseResult.warn("未授权的登陆");
	}
	
    /**
     * 登录方法
     * @param userInfo
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public APIBaseResult login(String username, String password, String code, Boolean rememberMe) {
    	if (StringUtils.isBlank(username)) {
    		return APIBaseResult.warn("用户名不能为空");
		}
    	Session session = super.getSession();
    	password = MD5Utils.encrypt(username.toLowerCase(), password);
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
        try {
            super.login(token);
            return  APIBaseResult.success(super.getSession().getId());
        } catch (IncorrectCredentialsException e) {
            return APIBaseResult.warn("密码错误");
        } catch (LockedAccountException e) {
            return APIBaseResult.warn("登录失败，该用户已被冻结");
        } catch (AuthenticationException e) {
            return APIBaseResult.warn("该用户不存");
        } catch (Exception e) {
            e.printStackTrace();
            return APIBaseResult.error(e.getMessage());
        }
    }

    /**
     * 未登录，shiro应重定向到登录界面，此处返回未登录状态信息由前端控制跳转页面
     * @return
     */
    @GetMapping(value = "/unauth")
    @ResponseBody
    public APIBaseResult unauth() {
		return APIBaseResult.getLogoutResult();
    }
    

    

}
